package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * <pre>
 * LOCATE(substr,str), LOCATE(substr,str,pos)
 *
 * The firstInNewCursor parser returns the position of the firstInNewCursor occurrence of substring substr in string str. The second parser returns the position of the firstInNewCursor occurrence of substring substr in string str, starting at position pos. Returns 0 if substr is not in str.
 *
 * mysql> SELECT LOCATE('bar', 'foobarbar');
 *         -> 4
 * mysql> SELECT LOCATE('xbar', 'foobar');
 *         -> 0
 * mysql> SELECT LOCATE('bar', 'foobarbar', 5);
 *         -> 7
 *
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月15日 下午2:37:28
 * @since 5.1.0
 */
public class Locate extends ScalarFunction {

    public Type getReturnType() {
        return Type.IntegerType;
    }

    public String[] getFunctionNames() {
        return new String[]{"LOCATE"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        String substr = Type.StringType.convert(args[0]);
        String str = Type.StringType.convert(args[1]);

        Integer pos = null;
        if (args.length == 3) {
            pos = Type.IntegerType.convert(args[2]);
        }
        if (pos == null) {
            return str.indexOf(substr) + 1;
        } else {
            return str.indexOf(substr, pos + 1) + 1;
        }

    }

}
